<template>
  <base-dialog ref="dialog" title="确认出车">
    <template #default="{ close }">
      <uni-forms ref="form" :model="form" label-position='top' label-width="150"
                 style="width: 100%;">
        <uni-forms-item :rules="[{ required: true, errorMessage: '请选择出车时间'}]" label="出车时间"
                        name="departureTime" required>
          <uni-datetime-picker v-model="form.departureTime" :border="false" :clear-icon="false"
                               :input-border="false" type="datetime"/>
        </uni-forms-item>
        <uni-forms-item :rules="[{ required: true, errorMessage: '获取定位失败'}]" label="当前定位" name="location">
          <uni-easyinput v-model="form.location" :input-border="false"
                         :styles="{ disableColor: '#fff', color: '#666666'}"
                         auto-height disabled placeholder="请输入" type="text"/>
        </uni-forms-item>
        <uni-forms-item label="电子围栏" name="enclosure">
          <uni-easyinput v-model="form.enclosure" :input-border="false"
                         :styles="{ disableColor: '#fff', color: '#666666'}"
                         disabled placeholder="请输入" type="text">
            <template #right>米</template>
          </uni-easyinput>
        </uni-forms-item>

        <view class="btn-group">
          <!-- <button class="main-btn" @click="submit()">确认出车</button> -->
          <view class="main-btn middle" @click="submit()">确认出车</view>
        </view>
      </uni-forms>
    </template>
  </base-dialog>
</template>

<script>
import {TaskPlanApi as Api} from "@/comms/api/taskPlanApi";
import {DateUtil, GeoUtils, LocationUtils, Msg} from "@/utils/BaseUtils";

export default {
  data() {
    return {
      form: {},
      vehicleList: []
    };
  },
  emits: ["done"],
  methods: {
    async open(data = {}) {
      Msg.loading(async closeLoading => {
        this.form = {id: data.id};
        this.form.departureTime = DateUtil.getCurrDateTime();
        this.form.enclosure = 0; 
        this.$refs.dialog.open();
        try {
          const location = await LocationUtils.getLocation();
          console.log('当前位置信息：', location);
          this.form.location = location.address;
          this.form.locationInfo = location;
        } catch (error) {
          Msg.error("获取定位信息时出错")
          console.error('获取定位信息时出错：', error);
        } finally {
          await Api.electronicFence().then(({data = {}}) => {
            this.form.enclosure = data.electronicFence;
            this.form.latitude = data.latitude;
            this.form.longitude = data.longitude;
          });
          closeLoading?.();
        }
      })
    },
    async validate(handler) {
      this.$refs.form.validate()
          .then(() => {
            handler && handler(() => this.$refs.dialog.close());
          }).catch(() => ({}))
    },

    submit(handler) {
      this.validate(close => {
        const {form = {}} = this;
        // 计算是否在电子围栏内
        if (form.enclosure > 0) {
          const {locationInfo = {}} = form;
          const distance = GeoUtils.calculateDistance({lat: form.latitude, lon: form.longitude},
              {lat: locationInfo.latitude, lon: locationInfo.longitude});
          if (distance > (form.enclosure * 1.3)) {
            return Msg.error("您不在围栏区间内")
          }
        }
        Api.departure({...form}).then(res => {
          handler?.();
          close?.();
          Msg.success("确认出车成功");
          this.$emit("done")
        })
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.main-btn{
	width: 700rpx;
	height: 100rpx;
	background: #1763fc;
	border-radius: 10rpx;
	font-size: 30rpx;
	color: #fff;
}
</style>
